<?php

// $Id$

require_once('../../boot.inc.php');
boot('my_site');

// discarding output buffering
ob_end_clean();

require_once(TANGRA_MAIN_DIR.'filesystem_toolbox/filesystem_functions.inc.php');

require_once($WSC->get_site_inc_dir().'modules/tangra_cms/classes/settings/tcms_settings_images_dbc.class.php');
require_once($WSC->get_site_inc_dir().'modules/tangra_cms/classes/image/tcms_image_dbc.class.php');


//session_start();

global $_SITE_DBC_PNT;

$context = new Web_Context();

if ($context->exists_in_get('imgid')) {
	$settings_images = new TCMS_Settings_Images_DBC();
	$dbc = $_SITE_DBC_PNT;
	if (!$settings_images->load_by_id($dbc, 1)) {
		throw new Tangra_Module_Exception('Cannot load images settings.');
	}

	$image_id = trim($context->get_from_get('imgid'));


	$image = new TCMS_Image_DBC();
	if ($image->load_by_id($dbc, $image_id)) {
		$filename_first = $WSC->get_uploads_dir().$settings_images->get_upload_path().$image->get_filename();
		if ($context->exists_in_get('imgvar')) {
			$variant = (string) $context->get_from_get('imgvar');
		} else {
			$variant = '';
		}

		switch ($variant) {
			case 'fix':
				$filename = $filename_first.TCMS_Image::FIXED_SIZE_IMAGE_SUFFIX.'.jpg';
				break;
			case 't1':
				$filename = $filename_first.TCMS_Image::THUMBNAIL1_IMAGE_SUFFIX.'.jpg';
				break;
			case 't2':
				$filename = $filename_first.TCMS_Image::THUMBNAIL2_IMAGE_SUFFIX.'.jpg';
				break;
			case 'orig':
				$filename = $filename_first.TCMS_Image::ORIGINAL_IMAGE_SUFFIX . '_' .$image->get_orig_filename();
				break;
			case '':
			default:
				$filename = $filename_first.'.jpg';
				break;
		}

		if (file_exists($filename)) {

			$file_extension = strtolower(substr(strrchr($filename,"."),1));
			switch ($file_extension) {
	//		   case "pdf": $ctype="application/pdf"; break;
	//		   case "exe": $ctype="application/octet-stream"; break;
	//		   case "zip": $ctype="application/zip"; break;
	//		   case "doc": $ctype="application/msword"; break;
	//		   case "xls": $ctype="application/vnd.ms-excel"; break;
	//		   case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
			   case "gif": $ctype="image/gif"; break;
			   case "png": $ctype="image/png"; break;
			   case "jpe": case "jpeg":
			   case "jpg": $ctype="image/jpeg"; break;
			   default: $ctype="";
			}

			if ($ctype) {
				header('Last-Modified: '.date('r'));
				header('Accept-Ranges: bytes');
				header('Content-Length: '.filesize($filename));
				header('Content-Disposition: inline; filename="'.$image->get_orig_filename().'"');
				header("Content-Type: $ctype");
				readfile("$filename") or die("File not found.");
			}
		} else {
			printbr('Cannot find image.');
		}
	} else {
		pritnbr('Cannot load image with id = ');
	}
}
